package ru.ivanovak.aptu.ccheckers;

import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;

public class Coin extends GameObject {
	private boolean isSelected = false;
	private GameView gameView;
	private Bitmap selectedBmp;
	private Bitmap bmp;
	private int row = 0;
	private int lastPokeI;
	private int lastPokeJ;
	private int column = 0;
	private final List<List<GameObject>> gameMatrix;
	
	public static final int WIDTH = 60;
	public static final int HEIGHT = 60;
	
	public Coin(GameView gv, Bitmap bmpp, Bitmap selectedBmpp, int irow, int icolumn,
			List<List<GameObject>> gameMatrixp) {
		gameView = gv;
		selectedBmp = selectedBmpp;
		bmp = bmpp;
		column = icolumn;
		row = irow;
		gameMatrix = gameMatrixp;
	}
	
	public void setXY(int nrow , int ncolumn) { row = nrow; column = ncolumn; }
	
	public void onDraw(Canvas c) {
		if (isSelected)
			c.drawBitmap(selectedBmp, column * WIDTH, row * HEIGHT, null);
		else
			c.drawBitmap(bmp, column * WIDTH, row * HEIGHT, null);
	}

	@Override
	public void poked(int i, int j) {
		lastPokeI = i;
		lastPokeJ = j;
		if (column == j && row == i)
			isSelected = !isSelected;
		else if (isSelected) 
			gameMatrix.get(i).get(j).redirect(this);
	}
	
	@Override
	public void accept(Field.Space space) {
		if (!((Math.abs(lastPokeI - row) == 2 && lastPokeJ == column) ||
				(Math.abs(lastPokeJ - column) == 2 && lastPokeI == row))) {
			return;
		}
		
		int ri = (lastPokeI + row) / 2;
		int rj = (lastPokeJ + column) / 2;
		if (!(gameMatrix.get(ri).get(rj) instanceof Coin))
			return;
		gameMatrix.get(ri).set(rj, new Field.Space());
		gameMatrix.get(row).set(column, new Field.Space());
		setXY(lastPokeI, lastPokeJ);
		gameMatrix.get(row).set(column, this);
		isSelected = false;
	}
	
	@Override
	public void accept(Coin coin) {
		isSelected = false;
	}
	
	@Override
	public void accept(Field.DeadZone coin) {
		//isSelected = false;
	}
	
	@Override 
	public void redirect(GameObject go) {
		go.accept(this);
	}
}
